import React from 'react';
import {Link} from 'react-router-dom';
import {fetch} from '@utils/Fetch';
import {result} from '@utils/Result';
import {ImagePicker, Tag, Toast} from 'antd-mobile';
import Preview from '@container/preview';

class UploadImage extends React.PureComponent {
  constructor(props) {
    super(props);
    const query = props.location.state || {};
    this.back = query.back || {};
    this.caseId = query.caseId;
  }

  state = {
    regions: [],
    files: [],
    selected: '',
    previewVisible: false,
    preview: null
  };

  componentDidMount() {
    this.fLoad();
  }

  componentWillUnmount() {
    Toast.hide();
  }

  fLoad = () => {
    if (!this.caseId) return false;
    fetch(`/api/region?caseId=${this.caseId}`).get()
      .success(res => this.setState({regions: res.content || []}));
  };
  fChange = (selected) => {
    this.setState({selected});
  };
  fSelectFile = (files, type, index) => {
    this.setState({files});
  };
  fUpload = async () => {
    const {selected, files = []} = this.state;
    if (!selected) {
      Toast.fail('请选择区域', 1);
      return false;
    }
    if (files.length === 0) {
      Toast.fail('请选择图片', 1);
      return false;
    }
    Toast.loading('上传中...', 0);
    const promises = files.map(({file}) => {
      const formData = new FormData();
      formData.append('file', file);
      return fetch(`/api/file?bucket=mh`).upload(formData);
    });
    const urls = [];
    promises.forEach(async p => {
      const res = await p;
      (result().success(res => urls.push(res.content.url)).end())(res);
      if (promises.length === urls.length) {
        this.fSave(urls);
      }
    });
  };
  fSave = (urls) => {
    const {history} = this.props;
    const {selected} = this.state;
    fetch('/api/material')
      .post({regionId: selected, urls, caseId: this.caseId})
      .success(res => {
        Toast.hide();
        res.message && Toast.success(res.message, 1);
        history.replace({pathname: '/home/case/material', state: {caseId: this.caseId}});
      });
  };
  fImageClick = (index, files) => {
    const file = files[index];
    if (file) {
      this.setState({preview: {url: file.url}, previewVisible: true});
    }
  };
  fClose = () => {
    this.setState({preview: null, previewVisible: false});
  };

  render() {
    const {regions, selected, files, preview, previewVisible} = this.state;
    return (
      <div className='cm-upload'>
        <div className='cm-upload-header'>
          <div className='cmuh-left'>
            <Link to={this.back} replace>取消</Link>
          </div>
          <div className='cmuh-right' onClick={this.fUpload}>
            上传
          </div>
        </div>
        <div className='cm-upload-content'>
          <div className='cmu-region'>
            {regions.map(r => (
              <Tag key={r._id}
                   selected={selected === r._id}
                   onChange={this.fChange.bind(this, r._id)}
              >{r.text}</Tag>
            ))}
          </div>
          <ImagePicker
            files={files}
            onChange={this.fSelectFile}
            multiple
            accept='image/gif,image/jpeg,image/jpg,image/png'
            onImageClick={this.fImageClick}
          />
        </div>
        {preview && previewVisible ? (
          <Preview visible={previewVisible}
                   onClose={this.fClose}
                   url={preview.url}
                   isLazy={false}
                   _id={preview._id}
          />
        ) : null}
      </div>
    )
  }
}

export default UploadImage;
